<template>
  <div class="search-container">
    <!-- 顶部搜索框 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText"></search-result>

    <!-- 联想建议 -->
    <search-suggest
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggest>

    <!-- 历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @clearAllSearch="searchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResult from './components/SearchResult.vue'
import SearchSuggest from './components/SearchSuggest.vue'

import { setItem, getItem } from '@/utils/storage'

export default {
  name: 'SearchIndex',
  components: { SearchHistory, SearchSuggest, SearchResult },
  data() {
    return {
      searchText: '', // 搜索文本
      isResultShow: false, // 是否展示搜索结果
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [] // 搜索历史数据内容
    }
  },
  methods: {
    onSearch(val) {
      this.searchText = val

      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }

      this.searchHistories.unshift(val)

      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    }
  },
  watch: {
    searchHistories(val) {
      // val 可以拿到监视到更改的最新数据
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }

  .search-form {
    position: fixed;
    right: 0;
    left: 0;
    top: 0;
    z-index: 1;
  }
}
</style>
